package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.code.CodeEmail;
import com.example.demo.code.CodeUser;
import com.example.demo.pojo.Root;
import com.example.demo.pojo.WorkUser;
import com.example.demo.server.UserServer;
import com.example.demo.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    UserServer userserver;
    @CrossOrigin
    @PostMapping(value = "api/login")
    @ResponseBody
    public CodeUser login(@RequestBody JSONObject json) {
        String id= json.getString("username");
        String pwd=json.getString("password");
        return userserver.userLogin(id,pwd);
    }
    @CrossOrigin
    @PostMapping(value = "api/uploadAvatar")
    @ResponseBody
    public String uploadAvatar(@RequestBody MultipartFile file) {

        return FileUtil.getFilePath(file,"E:\\代码\\ASP.net Web程序设计\\web程序设大作业\\后端\\workspace\\userAvatar","http://localhost:8443/api/avatar/",".jpg");
    }
    @CrossOrigin
    @PostMapping(value = "api/sendEmail")
    @ResponseBody
    public CodeEmail uploadAvatar(@RequestBody  JSONObject json) {
            String email= json.getString("email");
            CodeEmail codeEmail=new CodeEmail();
            try {
               String s=userserver.sendSimpleMail(email);
               codeEmail.setCode(200);
               codeEmail.setEmailNum(s);
            }
            catch (Exception e){
                codeEmail.setCode(400);
            }
            return codeEmail;

    }
    @CrossOrigin
    @PostMapping(value = "api/userRegister")
    @ResponseBody
    public CodeUser userRegister(@RequestBody WorkUser user){
        user.setType("user");
        return userserver.userRegister(user);
    }
    @CrossOrigin
    @PostMapping(value = "api/userRoot")
    @ResponseBody
    public List<Root> getUserRootList(@RequestBody JSONObject json){
        String type=json.getString("type");
        List<Root> S=new ArrayList<>();
        try {
            S=userserver.getUserRootList(type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return S;
    }


}
